<template>
  <div class="page-main">
    <a-layout :class="isFullScreen" style="height: 100%">
      <a-layout-content style="padding-right: 20px">
        <query-page
          ref="queryPageRef"
          v-model:selectedKeys="selectedKeys"
          :form-component-config="formComponentConfig"
          :form-render-config="formRenderConfig"
          :form-render-keys="renderKeys"
          :table-component-config="tableComponentConfig"
          :table-render-config="tableRenderConfig"
          :table-render-keys="tableRenderKeys"
          :loading="isLoading"
          :data="renderData"
          :total="total"
          title="检验结论登记"
          @query-data="getData"
        >
          <!-- @row-click="handleCheck" -->
          <template #top-container>
            <a-tabs v-model="activeKey" @change="changeKey">
              <a-tab-pane key="finishedProduct" title="成品" />
              <a-tab-pane key="rawMaterial" title="原材料" />
              <a-tab-pane key="standardParts" title="标准件" />
              <a-tab-pane key="spareParts" title="零组件" />
              <a-tab-pane key="forgedCastings" title="锻铸件" />
            </a-tabs>
          </template>
          <template #secretLevelName="{ record }">
            <secretLevelInfo
              :record="{
                secretLevel: record.secretLevel,
                secretLevelName: record.secretLevelName,
              }"
            />
          </template>
          <template #operate="{ record }">
            <a-button
              v-permission="['pms:check-bill:back']"
              :hidden="!['5', '10'].includes(record.billStatus)"
              type="text"
              @click="returnClick(record)"
              >退回</a-button
            >
            <a-button
              v-permission="['pms:check-bill:saveCheckCertification']"
              :hidden="!['10'].includes(record.billStatus)"
              type="text"
              @click="handleEdit(record)"
              >检验登记</a-button
            >
            <a-button
              v-permission="['pms:check-bill:doApplyInInv']"
              :hidden="!['13'].includes(record.billStatus)"
              type="text"
              @click="handleWarehousing(record)"
              >申请入库</a-button
            >
            <a-button
              :hidden="!['13', '15', '25'].includes(record.billStatus)"
              type="text"
              @click="handleDetail(record)"
              >登记详情</a-button
            >
          </template>
        </query-page>
      </a-layout-content>
    </a-layout>
    <a-modal
      :visible="visible"
      title="退回"
      @cancel="handleCancel"
      @ok="handleOk"
    >
      <a-form ref="formRef" :model="returnForm">
        <a-form-item
          field="rejectReason"
          label="退回原因"
          :rules="[{ required: true, message: '请填写退回原因后在进行退回！' }]"
        >
          <a-input v-model="returnForm.rejectReason" />
        </a-form-item>
      </a-form>
    </a-modal>
    <siderForm
      v-if="siderFormShow"
      ref="siderFormRef"
      :active-key="activeKey"
      :is-edit="isEdit"
      :sider-form-title="siderFormTitle"
      @handleClose="handleClose"
    />
  </div>
</template>

<script lang="ts" setup>
  import { ref, onMounted, nextTick, reactive } from 'vue';
  import {
    updateBack,
    getQueryPage,
    checkCertification,
    doApplyInInv,
  } from '@/api/admission/inspection';
  import { Message } from '@arco-design/web-vue';
  import secretLevelInfo from '@/common/components/secret-level-info/index.vue';
  import queryPage from '@/common/components/query-page/index.vue';
  import modalPromise from '@/common/utils/modal-promise';
  import {
    formRenderConfig,
    formComponentConfig,
  } from './form-comp/base-form-config';
  import {
    tableRenderConfig,
    tableComponentConfig,
  } from './table-comp/base-table-config';
  import siderForm from './component/sider-form.vue';
  import conTableCloums from './component/con-table-cloums';

  const formRef = ref();
  const isEdit = ref(true);
  const activeKey = ref('finishedProduct');
  const tabObj = ref({});
  const siderFormRef = ref(null);
  const siderFormTitle = ref('');
  const mdsItemType = ref(2);
  tabObj.value = {
    finishedProduct: [
      'checkTaskNo',
      'mdsVendorName',
      'mdsItemId',
      'marque',
      'parentItemSerialNo',
      'proMdsItemId',
      'billStatus',
      'prtlotNo',
      'receiveType',
      'planSourceType',
    ],
    rawMaterial: [
      'checkTaskNo',
      'mdsVendorName',
      'mdsItemId',
      'marques',
      'specs',
      'billStatus',
      'prtlotNo',
      'receiveType',
      'planSourceType',
    ],
    standardParts: [
      'checkTaskNo',
      'mdsVendorName',
      'mdsItemId',
      'billStatus',
      'prtlotNo',
      'receiveType',
      'planSourceType',
    ],
    spareParts: [
      'checkTaskNo',
      'mdsVendorName',
      'mdsItemId',
      'name13',
      'name14',
      'billStatus',
      'prtlotNo',
      'receiveType',
      'planSourceType',
    ],
    forgedCastings: [
      'checkTaskNo',
      'mdsVendorName',
      'mdsItemId',
      'billStatus',
      'prtlotNo',
      'receiveType',
      'planSourceType',
    ],
  };
  const visible = ref(false);

  const returnForm = reactive({
    // facprtlotNo: '',
    rejectReason: '',
  });
  const returnObj = ref({});
  const selectedKeys = ref();
  const tableRenderKeys = ref<any[]>([]);
  const init = () => {
    const key = `${activeKey.value}`;
    tableRenderKeys.value = conTableCloums[key];
  };
  init();
  const isLoading = ref(true);
  const renderData = ref<any[]>([]);
  const total = ref(0);

  const isFullScreen = ref('');
  const renderKeys = ref<any>([]);
  // const queryForms = ref();
  const siderFormShow = ref(false);
  renderKeys.value = tabObj.value.finishedProduct;
  const mdsItemTypeList = ref({
    finishedProduct: 2,
    rawMaterial: 3,
    standardParts: 1,
    spareParts: 4,
    forgedCastings: 5,
  });
  const changeKey = (data: any) => {
    mdsItemType.value = mdsItemTypeList.value[data];
    activeKey.value = data;
    renderKeys.value = tabObj.value[data];
    init();
    getData();
  };
  const getData = async (queryInfo: any = {}) => {
    isLoading.value = true;
    const params = {
      mdsItemType: mdsItemType.value,
      isAll: 0,
      ...queryInfo,
    };
    try {
      const { data } = await getQueryPage(params);
      if (data) {
        console.log(data);
        total.value = data.total;
        renderData.value = [...data.list];
      }
      isLoading.value = false;
    } catch (error) {
      Message.warning({
        content: error,
      });
    }
  };
  const returnClick = (record) => {
    visible.value = true;
    returnForm.rejectReason = '';
    returnObj.value = record;
  };
  const refresh = () => {
    getData();
  };
  const handleWarehousing = async (record: any) => {
    try {
      await modalPromise.warning({
        title: '请确认',
        content: '您确定要执行申请入库操作？',
        hideCancel: false,
      });
    } catch {
      return;
    }
    const { data } = await doApplyInInv(record);
    if (data) {
      Message.success('入库成功');
      refresh();
    }
  };
  const handleDetail = async (record: { id: string }) => {
    siderFormTitle.value = '登记详情';
    siderFormShow.value = true;
    isEdit.value = false;
    const { data } = await checkCertification(record.id);
    nextTick(() => {
      siderFormRef.value?.init(data);
    });
  };
  const handleEdit = (record: any) => {
    siderFormTitle.value = '检验登记';
    siderFormShow.value = true;
    isEdit.value = true;
    nextTick(() => {
      siderFormRef.value?.init(record);
    });
  };
  const handleClose = () => {
    siderFormShow.value = false;
    refresh();
  };
  const handleOk = () => {
    formRef.value.validate(async (validate: any) => {
      if (!validate) {
        if (returnObj.value?.billStatus === '11') {
          Message.warning('该数据状态为质量系统检验，不能退回！');
          return;
        }
        const params = {
          pmsCheckBillId: returnObj.value.pmsCheckBillId,
          pmsOrderId: returnObj.value.pmsOrderId,
          ...returnForm,
        };
        const { data } = await updateBack(params);
        if (data) {
          Message.success('退回成功');
          visible.value = false;
          refresh();
        }
        console.log(data);
      }
    });
  };
  const handleCancel = () => {
    visible.value = false;
  };
  onMounted(() => {
    getData();
  });
</script>

<style lang="less" scoped>
  /deep/ .arco-radio-group-button {
    width: 100%;
  }

  /deep/ .arco-radio-button {
    width: 50%;
    color: #4e5769 !important;
    text-align: center;
  }

  /deep/ .arco-radio-button.arco-radio-checked {
    color: #1e2228 !important;
  }
</style>
